const { ipcRenderer } = require('electron');

// DOM 元素
const sendBtn = document.getElementById('sendBtn');
const messageInput = document.getElementById('messageInput');
const replyContent = document.getElementById('replyContent');
const collapseBtn = document.getElementById('collapseBtn');
const closeBtn = document.getElementById('closeBtn');
const replyContainer = document.getElementById('replyContainer');

// 状态管理
let isCollapsed = false;
let isLoading = false;
let messageHistory = [];

// 初始化
function init() {
    console.log('应用初始化开始');
    
    // 检查字体支持
    const testDiv = document.createElement('div');
    testDiv.style.fontFamily = 'Microsoft YaHei';
    testDiv.textContent = '测试中文字体';
    testDiv.style.position = 'absolute';
    testDiv.style.visibility = 'hidden';
    document.body.appendChild(testDiv);
    
    const computedStyle = window.getComputedStyle(testDiv);
    console.log('当前字体:', computedStyle.fontFamily);
    document.body.removeChild(testDiv);
    
    setupEventListeners();
    setupStreamListeners(); // 初始化流式监听器
    loadMessageHistory();
    focusInput();
    
    console.log('应用初始化完成');
}



// 设置事件监听器
function setupEventListeners() {
    // 发送消息
    sendBtn.addEventListener('click', handleSendMessage);
    messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    });

    // 折叠/展开回复区域
    collapseBtn.addEventListener('click', toggleReplyContainer);

    // 窗口控制
    closeBtn.addEventListener('click', () => {
        ipcRenderer.invoke('close-app');
    });



    // 输入框自动聚焦
    messageInput.addEventListener('blur', () => {
        setTimeout(() => {
            if (!document.activeElement || document.activeElement === document.body) {
                focusInput();
            }
        }, 100);
    });

    // 防止右键菜单
    document.addEventListener('contextmenu', (e) => {
        e.preventDefault();
    });
}

// 流式回复相关变量
let currentStreamingMessage = null;
let streamingMessageElement = null;
let isStreaming = false;



// 处理发送消息 - 流式模式
async function handleSendMessage() {
    const message = messageInput.value.trim();
    if (!message || isLoading || isStreaming) return;

    // 清空输入框
    messageInput.value = '';
    
    // 使用流式发送
    await handleSendMessageStreaming(message);
}

// 流式发送消息
async function handleSendMessageStreaming(message) {
    // 显示加载状态
    setLoading(true);
    
    try {
        // 创建消息数据
        currentStreamingMessage = {
            id: Date.now(),
            userMessage: message,
            aiResponse: '',
            timestamp: new Date().toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            })
        };
        
        // 立即显示用户消息和空的AI回复
        streamingMessageElement = createStreamingMessageElement(currentStreamingMessage);
        replyContent.appendChild(streamingMessageElement);
        showReplyContainer();
        // 立即滚动到最底部
        replyContent.scrollTop = replyContent.scrollHeight;
        
        // 发送流式消息请求
        const result = await ipcRenderer.invoke('send-message-stream', message);
        
        if (!result.success) {
            // 如果流式请求失败，回退到阻塞式请求
            console.log('流式请求失败，回退到阻塞式请求');
            await handleSendMessageBlockingFallback(message);
        } else {
            isStreaming = true;
        }
        
    } catch (error) {
        console.error('流式发送消息失败:', error);
        showErrorMessage('网络连接失败，请检查网络设置');
        setLoading(false);
        focusInput();
    }
}

// 阻塞式发送消息
async function handleSendMessageBlocking(message) {
    // 显示加载状态
    setLoading(true);
    
    try {
        // 创建消息数据
        const messageData = {
            id: Date.now(),
            userMessage: message,
            aiResponse: '',
            timestamp: new Date().toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            })
        };
        
        const result = await ipcRenderer.invoke('send-message', message);
        
        if (result.success) {
            messageData.aiResponse = result.data.answer || '抱歉，我无法理解您的问题。';
            
            // 添加到历史记录
            messageHistory.push(messageData);
            saveMessageHistory();
            
            // 显示消息
            displayMessage(messageData);
            showReplyContainer();
            // 立即滚动到最底部
            replyContent.scrollTop = replyContent.scrollHeight;
        } else {
            let errorMessage = '发送失败，请稍后重试';
            if (result.error) {
                if (result.error.includes('ECONNREFUSED')) {
                    errorMessage = 'API服务器连接失败，请确保服务器正在运行';
                } else if (result.error.includes('timeout')) {
                    errorMessage = 'API请求超时，请检查网络状态';
                } else {
                    errorMessage = `请求失败：${result.error}`;
                }
            }
            showErrorMessage(errorMessage);
        }
    } catch (error) {
        console.error('阻塞式发送失败:', error);
        showErrorMessage('网络连接失败，请检查网络设置');
    } finally {
        setLoading(false);
        focusInput();
    }
}

// 流式回退到阻塞式（用于流式失败时）
async function handleSendMessageBlockingFallback(message) {
    try {
        const result = await ipcRenderer.invoke('send-message', message);
        
        if (result.success) {
            // 更新当前流式消息
            currentStreamingMessage.aiResponse = result.data.answer || '抱歉，我无法理解您的问题。';
            
            // 更新显示
            if (streamingMessageElement) {
                const textElement = streamingMessageElement.querySelector('.message-text');
                textElement.textContent = `答：${currentStreamingMessage.aiResponse}`;
                
                // 移除流式样式
                streamingMessageElement.classList.remove('streaming');
                
                // 替换为完整消息元素
                const newElement = createMessageElement(currentStreamingMessage);
                streamingMessageElement.parentNode.replaceChild(newElement, streamingMessageElement);
            }
            
            // 添加到历史记录
            messageHistory.push(currentStreamingMessage);
            saveMessageHistory();
        } else {
            let errorMessage = '发送失败，请稍后重试';
            if (result.error) {
                if (result.error.includes('ECONNREFUSED')) {
                    errorMessage = 'API服务器连接失败，请确保服务器正在运行';
                } else if (result.error.includes('timeout')) {
                    errorMessage = 'API请求超时，请检查网络状态';
                } else {
                    errorMessage = `请求失败：${result.error}`;
                }
            }
            showErrorMessage(errorMessage);
        }
    } catch (error) {
        console.error('回退阻塞式发送失败:', error);
        showErrorMessage('网络连接失败，请检查网络设置');
    } finally {
        // 重置流式状态
        isStreaming = false;
        currentStreamingMessage = null;
        streamingMessageElement = null;
        setLoading(false);
        focusInput();
    }
}

// 设置流式监听器
function setupStreamListeners() {
    // 移除之前的监听器
    ipcRenderer.removeAllListeners('stream-chunk');
    ipcRenderer.removeAllListeners('stream-complete');
    ipcRenderer.removeAllListeners('stream-error');
    
    // 处理流式数据块
    ipcRenderer.on('stream-chunk', (event, data) => {
        if (currentStreamingMessage && streamingMessageElement) {
            currentStreamingMessage.aiResponse = data.fullText;
            
            const textElement = streamingMessageElement.querySelector('.message-text');
            // 将"思考中..."替换为实际回复内容和光标
            textElement.innerHTML = `答：${escapeHtml(data.fullText)}<span class="streaming-cursor">|</span>`;
            
            // 滚动到底部
            setTimeout(() => {
                replyContent.scrollTop = replyContent.scrollHeight;
                adjustWindowSize();
            }, 10);
        }
    });
    
    // 处理流式完成
    ipcRenderer.on('stream-complete', (event, data) => {
        if (currentStreamingMessage) {
            currentStreamingMessage.aiResponse = data.fullAnswer;
            
            // 添加到历史记录
            messageHistory.push(currentStreamingMessage);
            saveMessageHistory();
            
            // 更新消息元素为完整版本
            if (streamingMessageElement) {
                const newElement = createMessageElement(currentStreamingMessage);
                streamingMessageElement.parentNode.replaceChild(newElement, streamingMessageElement);
            }
        }
        
        // 重置状态
        isStreaming = false;
        currentStreamingMessage = null;
        streamingMessageElement = null;
        setLoading(false);
        focusInput();
        
        setTimeout(() => {
            adjustWindowSize();
        }, 100);
    });
    
    // 处理流式错误
    ipcRenderer.on('stream-error', (event, data) => {
        console.error('流式响应错误:', data.error);
        showErrorMessage(`流式响应错误：${data.error}`);
        
        // 重置状态
        isStreaming = false;
        currentStreamingMessage = null;
        streamingMessageElement = null;
        setLoading(false);
        focusInput();
    });
}

// 显示消息
function displayMessage(messageData, prepend = false) {
    const messageElement = createMessageElement(messageData);
    
    if (prepend) {
        replyContent.insertBefore(messageElement, replyContent.firstChild);
    } else {
        replyContent.appendChild(messageElement);
        // 滚动到底部
        setTimeout(() => {
            replyContent.scrollTop = replyContent.scrollHeight;
        }, 100);
    }
    
    // 延迟调整窗口大小，确保DOM更新完成
    setTimeout(() => {
        adjustWindowSize();
    }, 150);
}

// 创建消息元素
function createMessageElement(messageData) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-item fade-in';
    messageDiv.dataset.messageId = messageData.id;
    
    // 只有当用户消息不为空时才显示用户问题
    const userMessageHtml = messageData.userMessage ? 
        `<div class="user-message">问：${escapeHtml(messageData.userMessage)}</div>` : '';
    
    messageDiv.innerHTML = `
        ${userMessageHtml}
        <div class="message-text">答：${escapeHtml(messageData.aiResponse)}</div>
        <div class="message-time">${messageData.timestamp}</div>
        <div class="message-actions">
            <button class="action-btn regenerate" title="重新生成" onclick="regenerateMessage('${messageData.id}')">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
            <button class="action-btn copy" title="复制" onclick="copyMessage('${messageData.id}')">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
        </div>
    `;
    
    return messageDiv;
}

// 创建流式消息元素（简化版本，用于流式显示）
function createStreamingMessageElement(messageData) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-item streaming fade-in';
    messageDiv.dataset.messageId = messageData.id;
    
    // 只有当用户消息不为空时才显示用户问题
    const userMessageHtml = messageData.userMessage ? 
        `<div class="user-message">问：${escapeHtml(messageData.userMessage)}</div>` : '';
    
    messageDiv.innerHTML = `
        ${userMessageHtml}
        <div class="message-text">答：<span class="thinking-text">思考中...</span></div>
        <div class="message-time">${messageData.timestamp}</div>
    `;
    
    return messageDiv;
}

// 重新生成消息
window.regenerateMessage = async function(messageId) {
    const messageData = messageHistory.find(msg => msg.id == messageId);
    if (!messageData || isLoading) return;
    
    setLoading(true);
    
    try {
        const result = await ipcRenderer.invoke('send-message', messageData.userMessage);
        
        if (result.success) {
            // 更新消息数据
            messageData.aiResponse = result.data.answer || '抱歉，我无法理解您的问题。';
            messageData.timestamp = new Date().toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
            
            // 更新显示
            const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
            if (messageElement) {
                const textElement = messageElement.querySelector('.message-text');
                const timeElement = messageElement.querySelector('.message-time');
                
                textElement.textContent = messageData.aiResponse;
                timeElement.textContent = messageData.timestamp;
                
                // 添加更新动画
                messageElement.classList.add('fade-in');
                setTimeout(() => {
                    messageElement.classList.remove('fade-in');
                }, 300);
            }
            
            saveMessageHistory();
        } else {
            showErrorMessage('重新生成失败，请稍后重试');
        }
    } catch (error) {
        console.error('重新生成失败:', error);
        showErrorMessage('重新生成失败，请检查网络连接');
    } finally {
        setLoading(false);
    }
};

// 复制消息
window.copyMessage = function(messageId) {
    const messageData = messageHistory.find(msg => msg.id == messageId);
    if (!messageData) return;
    
    navigator.clipboard.writeText(messageData.aiResponse).then(() => {
        // 显示复制成功提示
        showToast('已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
        showToast('复制失败');
    });
};

// 显示/隐藏回复容器
function showReplyContainer() {
    replyContainer.classList.add('show');
    isCollapsed = false;
    collapseBtn.textContent = '−';
    // 延迟调整窗口大小，确保CSS动画完成
    setTimeout(() => {
        adjustWindowSize();
    }, 350);
}

function hideReplyContainer() {
    replyContainer.classList.remove('show');
    adjustWindowSize();
}

// 切换回复容器
function toggleReplyContainer() {
    isCollapsed = !isCollapsed;
    
    if (isCollapsed) {
        replyContent.style.display = 'none';
        collapseBtn.textContent = '+';
    } else {
        replyContent.style.display = 'block';
        collapseBtn.textContent = '−';
    }
    
    adjustWindowSize();
}

// 设置加载状态
function setLoading(loading) {
    isLoading = loading;
    sendBtn.disabled = loading;
    
    // 不再使用悬浮的加载指示器
    // "思考中..."现在直接显示在AI回复位置
}

// 显示错误消息
function showErrorMessage(message) {
    const errorData = {
        id: Date.now(),
        userMessage: '',
        aiResponse: `❌ ${message}`,
        timestamp: new Date().toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        })
    };
    
    displayMessage(errorData);
    showReplyContainer();
}

// 显示提示消息
function showToast(message) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 12px;
        z-index: 1000;
        opacity: 0;
        transition: opacity 0.3s ease;
    `;
    
    document.body.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.style.opacity = '1';
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 2000);
}

// 调整窗口大小
function adjustWindowSize() {
    // 使用实际 DOM 高度计算以提高准确性
    let totalHeight = document.querySelector('.app-container').clientHeight;
    
    // 添加额外 padding 以确保输入框完全显示
    totalHeight += 20; // 额外 20px 以覆盖任何边距或边框
    
    // 最小高度
    totalHeight = Math.max(totalHeight, 80);
    
    // 最大高度限制
    totalHeight = Math.min(totalHeight, 600);
    
    console.log('调整窗口大小:', totalHeight);
    ipcRenderer.invoke('resize-window', 400, totalHeight);
    
    // 强制重新布局以修复交互位置
    setTimeout(() => {
        window.dispatchEvent(new Event('resize'));
    }, 100);
}

// 聚焦输入框
function focusInput() {
    setTimeout(() => {
        messageInput.focus();
    }, 100);
}

// 转义HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 保存消息历史
function saveMessageHistory() {
    localStorage.setItem('messageHistory', JSON.stringify(messageHistory.slice(-10))); // 只保存最近10条
}

// 加载消息历史
function loadMessageHistory() {
    try {
        const saved = localStorage.getItem('messageHistory');
        if (saved) {
            messageHistory = JSON.parse(saved);
            
            // 显示历史消息
            messageHistory.forEach(msg => {
                displayMessage(msg, false);
            });
            
            if (messageHistory.length > 0) {
                showReplyContainer();
            }
        }
    } catch (error) {
        console.error('加载消息历史失败:', error);
        messageHistory = [];
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

// 窗口失去焦点时保持输入框聚焦
window.addEventListener('blur', () => {
    setTimeout(focusInput, 100);
});

// 防止拖拽文件
document.addEventListener('dragover', (e) => {
    e.preventDefault();
});

document.addEventListener('drop', (e) => {
    e.preventDefault();
});